<?php

	include_once("./db.php"); 
	
	$userId = $_SESSION["user"]["Id"];

	$olderCombinationId = $_REQUEST["olderCombinationId"];
	$newerCombinationId = $_REQUEST["newerCombinationId"];
	
	$res = db_select("SELECT 
		c.Id CombinationId,
		p.Id ProductId,
		p.Name ProductName,
		GROUP_CONCAT(e.Id) ElementId,
		GROUP_CONCAT(e.Name) ElementName,
		u.Name UserName,
		TIME_TO_SEC(TIMEDIFF(NOW(), c.CreateDate)) CreateDate
		FROM
			Combination c,
			CombinationItem ci,
			User u,
			Element p,
			Element e
		WHERE
			ci.CombinationId = c.Id AND
			c.AuthorId = u.Id AND
			p.Id = c.ProductId AND
			e.Id = ci.ElementId AND
			NOT p.Enabled	AND
			c.Id BETWEEN @olderCombinationId and @newerCombinationId
		GROUP BY p.Id	
		ORDER BY c.CreateDate $order",
		array(
			"newerCombinationId" => $newerCombinationId,
			"olderCombinationId" => $olderCombinationId
		)
		);
		//	AND NOT p.Enabled
	//TODO:Dynamic LIMIT 2

	while($item = mysql_fetch_array($res, MYSQL_ASSOC))
		$ret["Elements"][] = $item;
		
	for($i = 0; $i < count($ret["Elements"]); $i++)
	{
	//	print_r($ret["Elements"][$i]["CombinationId"]);
	
		$ret["Elements"][$i]["Elements"]["Id"] = explode(",", $ret["Elements"][$i]["ElementId"]);
		$ret["Elements"][$i]["Elements"]["Name"] = explode(",", $ret["Elements"][$i]["ElementName"]);
		
		$res = db_select("SELECT v.Id, Message, TIME_TO_SEC(TIMEDIFF(NOW(), v.CreateDate)) CreateDate, CASE v.AuthorId WHEN $userId THEN 'Me' ELSE Name end as Name,  v.AuthorId
			FROM
				Vote v,
				User u
			WHERE
				Message IS NOT NULL AND
				u.Id = v.AuthorId AND
				v.CombinationId = " . $ret["Elements"][$i]["CombinationId"]. "
				ORDER BY v.CreateDate");
				
			while($item = mysql_fetch_array($res, MYSQL_ASSOC))
				$ret["Elements"][$i]["Comments"][] = $item;
					
					
		$res = db_scalar("SELECT COALESCE(SUM(Value)-1, -1)
		FROM Vote
		WHERE
		CombinationId = " . $ret["Elements"][$i]["CombinationId"]);
		
		$ret["Elements"][$i]["Votes"]["Value"] = $res;			
		
		$res = db_scalar("SELECT 
		
		CASE u.Id WHEN $userId THEN 'You' ELSE Name end as Name,
		CASE u.Id WHEN $userId THEN 0 ELSE 1 end as User
			FROM
				Vote v,
				User u
			WHERE
				u.Id = v.AuthorId AND
				v.CombinationId = " . $ret["Elements"][$i]["CombinationId"]. " AND
				Value > 0
				ORDER BY 
				User, 
				v.CreateDate DESC");
		
		$ret["Elements"][$i]["Votes"]["Name"] = $res;			
			
			
	}
	
	
	//print_r($ret);
	
	echo json_result_encode($ret);

?>

